/**
 * Created by RT007 on 2016/7/16.
 */
angular.module('app').directive('myDatepicker', function ($compile) {
    var controllerName = 'dateEditCtrl';
    return {
        restrict: 'A',
        require: '?ngModel',
        scope: true,
        terminal: true,
        priority: 1,
        compile: function (element) {
            var wrapper = angular.element(
                '<div class="input-group">' +
                '<span class="input-group-btn">' +
                '<button type="button" class="btn btn-default" ng-click="' + controllerName + '.openPopup($event)"><i class="glyphicon glyphicon-calendar"></i></button>' +
                '</span>' +
                '</div>');

            function setAttributeIfNotExists(name, value) {
                var oldValue = element.attr(name);
                if (!angular.isDefined(oldValue) || oldValue === false) {
                    element.attr(name, value);
                }
            }

            setAttributeIfNotExists('type', 'text');
            setAttributeIfNotExists('is-open', controllerName + '.popupOpen');
            setAttributeIfNotExists('datepicker-popup', 'yyyy-MM-dd');
            setAttributeIfNotExists('readonly', true);
            setAttributeIfNotExists('close-text', '關閉');
            setAttributeIfNotExists('clear-text', '清除');
            setAttributeIfNotExists('current-text', '今天');

            element.addClass('form-control');
            element.removeAttr('my-datepicker');
            element.after(wrapper);
            wrapper.prepend(element);

            return function (scope, element) {
                $compile(element)(scope);
            };
        },
        controller: function () {
            this.popupOpen = false;
            this.openPopup = function ($event) {
                $event.preventDefault();
                $event.stopPropagation();
                this.popupOpen = true;
            };
        },
        controllerAs: controllerName
    };
});